import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
@Component({
    selector: 'sa-car-outsource',
    templateUrl: './car-outsource.component.html',
    styleUrls: ['./car-outsource.css']
})
export class carOutsourceComponent implements OnInit {
    tableData: any[] = []; //table数据
    totalCount: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    searchKey: string = ''; //搜索keyword
    btnData: any[] = [];
    carAdd: boolean = false;
    carEdit: boolean = false;
    carDeleteBatch: boolean = false;
    carStation: boolean = false;
    carItinerary: boolean = false;
    modal: any = { //图片弹窗
        picture: '',
        carNumber: ''
    };
    selectedCompanyName: string = ''; //公司名称
    selectedCompanyId: string = ''; //公司ID
    useTypeL1: string = ''; //useTypeL1  select值
    useTypeL2: string = ''; //useTypeL2  select值
    sensorType: string = ''; //传感器类型参数
    carTypeDetailList: any = []; //useTypeL2数据
    carTypeList = carTypeListObj.carTypeList
    carUseList = carTypeListObj.carUseList
    carDeatailUseList = carTypeListObj.carDeatailUseList
    startTime: string = '';
    endTime: string = '';
    isViewer: boolean = false; //默认隐藏
    jumpData:any; // 跳转页面接收到的数据
    initDateRange: any = {
        startTime:'',
        endTime:'',
    }// 时间组件需要渲染的值
    companyData:any = {
        companyId:'',
        companyName:'',
    }
    constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
        activatedRoute.queryParams.subscribe(queryParams => {
            this.curPage = queryParams.nowPage || 1;
            if(common.getCookie('jumpTo/system/car')){
                this.jumpData = JSON.parse(common.getCookie('jumpTo/system/car'));
                this.initDateRange.startTime = this.jumpData.startTime;
                this.initDateRange.endTime = this.jumpData.endTime;
                this.companyData.companyId = this.selectedCompanyId = this.jumpData.companyId;
                this.companyData.companyName = this.selectedCompanyName = this.jumpData.companyName;
                this.searchKey = this.jumpData.deviceId;
            }
        });
    }
    //请求传感器类型的接口
	querySensor(){
		this.jsonApiService.http('sensorManage/querySensorList.html','').subscribe(data=> {
			if(data.success){
				this.inputParam = data.data
			}
		})
	}
	inputParam: any = []; 
    //组件传回来 传感器类型
    sensorSelected(data){
        this.sensorType = data.sensorType;
    }
    // 接收子组件传递过来的数据 
    getSelectTableTime(time) {
        this.startTime = time.startTime;
        this.endTime = time.endTime;
    }
    //公司选中回调
    companySelected(data) {
        this.selectedCompanyId = data.companyId;
        this.selectedCompanyName = data.companyName;
    }
    ngOnInit() {
        let that = this;
        this.initBtn();
        if(this.inputParam.length == 0){this.querySensor();}// 请求传感器列表接口
        if(common.getCookie('jumpTo/system/car')) {
            setTimeout(()=>{
                that.load();
            },100)
            common.clearCookie('jumpTo/system/car');
        }else{
            this.load();
        }
        System.import('assets/js/viewer/viewer.js').then(
            () => {
                System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                    () => {
                        System.import('assets/js/viewer/viewer.css').then(() => {})
                    })
            })
    }
    //导出
    exprotData() {
        var parameters = {
            searchKey: this.searchKey,
            useTypeL1: this.useTypeL1,
            useTypeL2: this.useTypeL2,
            companyId: this.selectedCompanyId,
            startTime: this.startTime,
            endTime: this.endTime,
            sensorType: this.sensorType,
        }
        let timeCheck = common.correctTime(parameters);
        if(!timeCheck.status) {
            this.jsonApiService.message(timeCheck.message);
            return;
        }
        common.exprotDataFile(parameters, 'param', config.BaseURL + 'deviceOutsource/exportOutsourceCarList.html')
    }
    ngOnDestroy() {
        document.onclick = null;
    }
    //table刷新
    refresh() {
        this.load();
    }
    //权限按钮
    initBtn() {
        this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:car')));
        if(!this.btnData) {
            return
        };
        for(let item of this.btnData) {
            if(item.sourceKey === "car:add" && item.parentId) {
                this.carAdd = true;
            }
            if(item.sourceKey === "car:edit" && item.parentId) {
                this.carEdit = true;
            }
            if(item.sourceKey === "car:deleteBatch" && item.parentId) {
                this.carDeleteBatch = true;
            }
            if(item.sourceKey === "car:station" && item.parentId) {
                this.carStation = true;
            }
            if(item.sourceKey === "car:itinerary" && item.parentId) {
                this.carItinerary = true;
            }
        }
    }
    //车辆用途change回调
    carUseTypeL1Change() {
        this.carTypeDetailList = [];
        this.useTypeL2 = '';
        for(let item of this.carTypeList) {
            if(item.id === this.useTypeL1) {
                this.carTypeDetailList = item.children;
                break;
            }
        }
    }
    //表格搜索
    table_search() {
        this.curPage = 1;
        this.searchKey = common.stringTrim(this.searchKey);
        this.load();
    }
    //初始化加载list数据
    load() {
        let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
        if(!timeCheck.status) {
            this.jsonApiService.message(timeCheck.message);
            return;
        }
        let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters: {
                startTime: this.startTime,
                endTime: this.endTime,
                searchKey: this.searchKey,
                useTypeL1: this.useTypeL1,
                useTypeL2: this.useTypeL2,
                companyId: this.selectedCompanyId,
                sensorType: this.sensorType
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(data);
        this.jsonApiService.http("deviceOutsource/findOutsourceCarList.html", reqdata).subscribe(data => {
            if(data.isSuccess) {
                for(let item of data.exhibitDatas) {
                    item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
                    item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
                }
                this.tableData = data.exhibitDatas;
                this.totalCount = data.recordCount;
            } else {
                this.jsonApiService.message(data.message);
            }
        })
    }
    getUseTypeNameL1(key) {
        if(key) {
            return this.carUseList[key];
        } else {
            return '';
        }
    }
    getUseTypeNameL2(key) {
        if(key) {
            return this.carDeatailUseList[key];
        } else {
            return '';
        }
    }
    imgInfo: any = []; //单个图片列表
    //查看照片
    open_img(row, val) {
        var that = this;
        this.imgInfo = [];

        if(this.isViewer && $(".viewer-container").length > 0) {
            this.viewer.destroy();
        }
        val.show();

        this.modal.carNumber = row.carNumber;

        for(var b = 0; b < row.imageInfo.length; b++) {
            row.imageInfo[b].localImg = [];
            for(let c = 0; c < row.imageInfo[b].imageList.length; c++) {
                let localImg;
                // if(row.imageInfo[b].imageList[c][0] == '/'){
                // 	localImg = config.BaseURL + row.imageInfo[b].imageList[c].substr(1);
                // }else{
                // 	localImg = config.BaseURL + row.imageInfo[b].imageList[c];
                // }
                if(row.imageInfo[b].imageList[c].indexOf('http') == -1) {
                    if(row.imageInfo[b].imageList[c][0]  ==  '/') {
                        localImg = config.BaseURL + row.imageInfo[b].imageList[c].substr(1);
                    } else {
                        localImg = config.BaseURL + row.imageInfo[b].imageList[c];
                    }
                } else {
                    localImg = row.imageInfo[b].imageList[c];
                }
                row.imageInfo[b].localImg.push(localImg);
            }
        }
        this.imgInfo = row.imageInfo
    }
    //关闭图片弹窗
    imgClose(val) {
        this.modal.carNumber = '';
        this.modal.picture = '';
        val.hide();
        // $(".imagesInfo").find('img').viewer('destroy');
    }
    //站点管理
    site_management(row) {
        this.router.navigate(['/system/car/car-station'], {
            queryParams: {
                companyId: row.companyId,
                deviceId: row.deviceId,
                carNumber: row.carNumber,
                nowPage: this.curPage
            }
        });
    }
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    //新建车辆
    new_car() {
        this.router.navigate(['/system/car/car-page'], {
            queryParams: {
                type: 'new'
            }
        });
    }
    //编辑车辆
    updata_car(row) {
        this.router.navigate(['/system/car/car-page'], {
            queryParams: {
                id: row.id,
                type: 'updata',
                nowPage: this.curPage
            }
        });
    }
    //删除车辆
    del_car(row) {
        this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
            let reqdata = 'ids=' + row.id;
            this.jsonApiService.http("car/deleteBatch.html", reqdata).subscribe(data => {
                this.jsonApiService.message(data.message);
                this.load();
            })
        })
    }
    bigImg: any = '' // 放大的图片
    //图片放大
    bigimg(modal, row) {
        // modal.show();
        this.bigImg = row
        if(this.isViewer && $(".viewer-container").length > 0) {
            System.import('assets/js/viewer/viewer.js').then(
                () => {
                    System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
                        () => {
                            System.import('assets/js/viewer/viewer.css').then(() => {
                                this.showImg();
                            })
                        })
                })
        } else {
            this.showImg();
        }

    }
    CloseBigImg(modal) {
        modal.hide();
    }
    //显示图片组件
    viewer: any = '';
    showImg() {
        var that = this;
        var imgList = $(".imagesInfo")[0];
        this.viewer = new Viewer(imgList, {
            url: 'src',
            title: function(image) {
                return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
            },
        });
        that.isViewer = true
    }
}